<template>
  <el-drawer
    v-model="drawerVisible"
    title="消息通知"
    :size="450"
    direction="rtl"
    @open="handleDrawerOpen"
  >
    <template #header>
      <div class="drawer-header">
        <span>消息通知</span>
        <div class="header-actions">
          <el-button
            text
            type="primary"
            size="small"
            @click="handleMarkAllRead"
            :disabled="notificationStore.unreadCount === 0 || notificationStore.loading"
            :loading="markingAllRead"
          >
            全部已读
          </el-button>
          <el-button
            text
            type="primary"
            size="small"
            :icon="Refresh"
            @click="handleRefresh"
            :loading="notificationStore.loading"
          >
            刷新
          </el-button>
        </div>
      </div>
    </template>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-select
        v-model="selectedType"
        placeholder="全部类型"
        size="small"
        clearable
        style="width: 120px; margin-right: 8px;"
        @change="handleFilterChange"
      >
        <el-option label="全部类型" value="" />
        <el-option label="信息" value="info" />
        <el-option label="成功" value="success" />
        <el-option label="警告" value="warn" />
        <el-option label="错误" value="error" />
      </el-select>
      
      <el-checkbox
        v-model="showUnreadOnly"
        size="small"
        @change="handleFilterChange"
      >
        仅未读
      </el-checkbox>
    </div>
    
    <!-- 通知列表 -->
    <div class="notification-list" v-loading="notificationStore.loading">
      <el-empty
        v-if="!notificationStore.loading && notificationStore.notifications.length === 0"
        description="暂无消息"
        :image-size="100"
      />
      
      <div
        v-for="notification in notificationStore.notifications"
        :key="notification.id"
        class="notification-item"
        :class="{ 'unread': !notification.is_read }"
        @click="handleItemClick(notification)"
      >
        <div class="notification-icon">
          <el-icon :size="20" :color="getTypeColor(notification.type)">
            <component :is="getTypeIcon(notification.type)" />
          </el-icon>
        </div>
        
        <div class="notification-content">
          <div class="notification-title">
            {{ notification.title }}
            <el-badge
              v-if="!notification.is_read"
              is-dot
              class="unread-dot"
            />
          </div>
          <div class="notification-message">{{ notification.message || notification.content }}</div>
          <div class="notification-time">
            {{ formatTime(notification.timestamp) }}
          </div>
        </div>
        
        <div class="notification-actions">
          <el-button
            text
            circle
            :icon="Close"
            size="small"
            @click.stop="handleRemove(notification.id)"
          />
        </div>
      </div>
      
      <!-- 加载更多 -->
      <div v-if="hasMore" class="load-more">
        <el-button
          text
          type="primary"
          :loading="loadingMore"
          @click="handleLoadMore"
        >
          加载更多
        </el-button>
      </div>
      
      <div v-else-if="notificationStore.notifications.length > 0" class="no-more">
        没有更多了
      </div>
    </div>
    
    <!-- 通知详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="currentNotification?.title"
      width="500px"
    >
      <div v-if="currentNotification" class="notification-detail">
        <div class="detail-meta">
          <el-tag :type="getTypeTagType(currentNotification.type)" size="small">
            {{ getTypeLabel(currentNotification.type) }}
          </el-tag>
          <span class="detail-time">{{ formatTime(currentNotification.timestamp) }}</span>
        </div>
        <div class="detail-content">
          {{ currentNotification.content || currentNotification.message }}
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useNotificationStore } from '@/stores/notification'
import { ElMessage } from 'element-plus'
import {
  SuccessFilled,
  WarningFilled,
  InfoFilled,
  CircleCloseFilled,
  Close,
  Refresh
} from '@element-plus/icons-vue'
import type { Notification } from '@/stores/notification'

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

const notificationStore = useNotificationStore()

const drawerVisible = computed({
  get: () => props.modelValue,
  set: (val: boolean) => emit('update:modelValue', val)
})

// 筛选条件
const selectedType = ref('')
const showUnreadOnly = ref(false)
const markingAllRead = ref(false)
const loadingMore = ref(false)
const detailDialogVisible = ref(false)
const currentNotification = ref<Notification | null>(null)

// 是否有更多数据
const hasMore = computed(() => {
  const { page, pageSize, total } = notificationStore.pagination
  return page * pageSize < total
})

// 监听抽屉打开，加载数据
watch(drawerVisible, (val: boolean): void => {
  if (val) {
    handleDrawerOpen()
  }
})

const handleDrawerOpen = (): void => {
  // 重置筛选条件
  selectedType.value = notificationStore.filters.type || ''
  showUnreadOnly.value = notificationStore.filters.unread || false
  
  // 加载通知列表
  if (notificationStore.notifications.length === 0) {
    notificationStore.fetchNotifications()
  }
}

const getTypeIcon = (type: string): any => {
  const iconMap: Record<string, any> = {
    success: SuccessFilled,
    warn: WarningFilled,
    warning: WarningFilled,
    info: InfoFilled,
    error: CircleCloseFilled
  }
  return iconMap[type] || InfoFilled
}

const getTypeColor = (type: string): string => {
  const colorMap: Record<string, string> = {
    success: '#67c23a',
    warn: '#e6a23c',
    warning: '#e6a23c',
    info: '#409eff',
    error: '#f56c6c'
  }
  return colorMap[type] || '#409eff'
}

const getTypeLabel = (type: string): string => {
  const labelMap: Record<string, string> = {
    success: '成功',
    warn: '警告',
    warning: '警告',
    info: '信息',
    error: '错误'
  }
  return labelMap[type] || '信息'
}

const getTypeTagType = (type: string): string => {
  const tagMap: Record<string, string> = {
    success: 'success',
    warn: 'warning',
    warning: 'warning',
    info: 'info',
    error: 'danger'
  }
  return tagMap[type] || 'info'
}

const formatTime = (timestamp?: string): string => {
  if (!timestamp) return ''
  
  const now = new Date()
  const time = new Date(timestamp)
  const diff = now.getTime() - time.getTime()
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) {
    return Math.floor(diff / 3600000) + '小时前'
  } else if (diff < 604800000) {
    return Math.floor(diff / 86400000) + '天前'
  } else {
    return time.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

const handleItemClick = async (notification: Notification): Promise<void> => {
  // 如果未读，先标记为已读
  if (!notification.is_read) {
    await notificationStore.markAsRead(notification.id)
  }
  
  // 显示详情
  try {
    const detail = await notificationStore.fetchNotificationDetail(notification.id)
    if (detail) {
      currentNotification.value = detail
      detailDialogVisible.value = true
    }
  } catch (error) {
    // 如果获取详情失败，使用当前通知数据
    currentNotification.value = notification
    detailDialogVisible.value = true
  }
}

const handleRemove = (id: string): void => {
  notificationStore.removeNotification(id)
  ElMessage.success('已移除')
}

const handleMarkAllRead = async (): Promise<void> => {
  markingAllRead.value = true
  try {
    await notificationStore.markAllAsRead()
  } finally {
    markingAllRead.value = false
  }
}

const handleRefresh = (): void => {
  notificationStore.refresh()
}

const handleFilterChange = (): void => {
  // 更新筛选条件
  notificationStore.setFilters({
    type: selectedType.value || '',
    unread: showUnreadOnly.value
  })
  
  // 重新加载数据
  notificationStore.refresh()
}

const handleLoadMore = async (): Promise<void> => {
  loadingMore.value = true
  try {
    await notificationStore.loadMore()
  } finally {
    loadingMore.value = false
  }
}
</script>

<style lang="scss" scoped>
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  
  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.filter-section {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
}

.notification-list {
  height: calc(100vh - 200px);
  overflow-y: auto;
  
  .notification-item {
    display: flex;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background-color 0.3s;
    position: relative;
    
    &:hover {
      background-color: #f5f5f5;
    }
    
    &.unread {
      background-color: #f0f9ff;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 3px;
        background-color: #409eff;
      }
    }
    
    .notification-icon {
      margin-right: 12px;
      flex-shrink: 0;
    }
    
    .notification-content {
      flex: 1;
      min-width: 0;
      
      .notification-title {
        font-size: 14px;
        font-weight: 600;
        color: #333;
        margin-bottom: 6px;
        display: flex;
        align-items: center;
        gap: 8px;
      }
      
      .notification-message {
        font-size: 13px;
        color: #666;
        margin-bottom: 6px;
        line-height: 1.5;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      
      .notification-time {
        font-size: 12px;
        color: #999;
      }
    }
    
    .notification-actions {
      margin-left: 12px;
      flex-shrink: 0;
    }
  }
  
  .load-more {
    padding: 16px;
    text-align: center;
  }
  
  .no-more {
    padding: 16px;
    text-align: center;
    color: #999;
    font-size: 12px;
  }
}

.notification-detail {
  .detail-meta {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
    
    .detail-time {
      color: #999;
      font-size: 13px;
    }
  }
  
  .detail-content {
    font-size: 14px;
    line-height: 1.8;
    color: #333;
    white-space: pre-wrap;
    word-break: break-word;
  }
}
</style>


